import store from './store'
import router, { asyncRoutes } from './router'
import NProgress from 'nprogress'

const whileList = ['/login']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      next()
      if (!store.state.user.userinfo.id) {
        const { menus, permissions } = await store.dispatch('user/getUserInfo')
        console.log(menus, permissions)
        const fileRoutes = asyncRoutes.filter(i => { return menus.includes(i.name) })
        console.log(fileRoutes)
        store.commit('user/SET_ROUTES', fileRoutes)
        router.addRoutes([...fileRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      }
    }
  } else {
    if (whileList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach((to, from) => {
  NProgress.done()
})
